<?php

declare(strict_types=1);

namespace app\controller\admin;

use app\model\RailwayStation as RailwayStationModel;
use app\model\CheckRecord as CheckRecordModel;
use app\model\CheckType as CheckTypeModel;
use app\model\CheckItem as CheckItemModel;
use app\model\Station as StationModel;
use app\model\Railway as RailwayModel;
use app\util\ReturnCode;
use think\facade\Db;

class Station extends Base
{
    public function down()
    {
        $ids = $this->request->post('ids', []);
        $rid = $this->request->post('rid', 0);
        $items = $this->request->post('items', []);
        $items = implode(',', $items);

        // 校验ids长度必须为2
        if (count($ids) !== 2) {
            return $this->buildFailed(ReturnCode::UPDATE_FAILED, '必须选择两个车站作为区间');
        }

        // 获取两个车站的排序信息
        $stations = RailwayStationModel::where([
            ['railway_id', '=', $rid],
            ['id', 'in', $ids]
        ])->order('sort', 'asc')->select()->toArray();

        if (count($stations) !== 2) {
            return $this->buildFailed(ReturnCode::UPDATE_FAILED, '选择的车站不存在');
        }

        // 检查两个车站是否相邻
        if ($stations[1]['sort'] - $stations[0]['sort'] !== 1) {
            return $this->buildFailed(ReturnCode::UPDATE_FAILED, '只能选择相邻的两个车站进行封锁');
        }

        // 检查区间内是否有非正常状态的车站
        $status = array_column($stations, 'status');
        if (in_array(2, $status) || in_array(3, $status) || in_array(4, $status)) {
            return $this->buildFailed(ReturnCode::UPDATE_FAILED, '区间内存在非正常状态的车站');
        }

        Db::startTrans();
        try {
            // 更新区间内所有车站状态
            $stationIds = array_column($stations, 'id');
            RailwayStationModel::where([
                ['railway_id', '=', $rid],
                ['id', 'in', $stationIds]
            ])->update(['status' => 2, 'check_item_ids' => $items]);

            // 生成一条检查记录
            $crid = CheckRecordModel::insertGetId([
                'railway_id' => $rid,
                'start_id' => $stations[0]['id'], // 使用排序靠前的站ID
                'end_id' => $stations[1]['id'],   // 使用排序靠后的站ID
                'range_ids' => implode(',', $stationIds), // 保存区间内所有站点ID
                'create_time' => time(),
            ]);

            // 获取检查类型
            $checkTypes = CheckTypeModel::where([
                ['status', '=', 1],
                ['id', 'in', $items],
            ])->select()->toArray();

            // 为区间生成检查项目
            foreach ($checkTypes as $checkType) {
                CheckItemModel::insert([
                    'check_record_id' => $crid,
                    'railway_id' => $rid,
                    'start_id' => $stations[0]['id'], // 使用排序靠前的站ID
                    'end_id' => $stations[1]['id'],   // 使用排序靠后的站ID
                    'direction' => $checkType['direction'],
                    'type_id' => $checkType['id'],
                    'type' => $checkType['type'],
                    'type_name' => $checkType['name'],
                    'create_time' => time(),
                ]);
            }

            Db::commit();
            return $this->buildSuccess();
        } catch (\Exception $e) {
            Db::rollback();
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '生成检查项目失败' . $e->getMessage());
        }
    }
    public function all()
    {
        $where = [
            ['status', '=', 1]
        ];
        $list = StationModel::where($where)
            ->field('id value,name')
            ->order('id', 'desc')
            ->select()
            ->toArray();
        return $this->buildSuccess($list);
    }
    public function lists()
    {
        $where = [];
        $status = $this->request->get('status', 0);
        $keywords = $this->request->get('keywords', '');
        $page = $this->request->get('page', 1, 'intval');
        $size = $this->request->get('size', 10, 'intval');
        if ($status) {
            $where[] = ['status', '=', $status];
        }
        if ($keywords) {
            $where[] = ['name', 'like', '%' . $keywords . '%'];
        }
        $list = StationModel::where($where)
            ->where($where)
            ->order('id', 'desc')
            ->paginate($size);
        $data = [
            'count' => $list->total(),
            'list' => $list->items()
        ];
        return $this->buildSuccess($data);
    }
    public function add()
    {
        $name = $this->request->post('name', '');
        $x = $this->request->post('x', 0);
        $y = $this->request->post('y', 0);
        $history = StationModel::where(['name' => $name])->find();
        if ($history) {
            return $this->buildFailed(ReturnCode::ADD_FAILED, '该车站已存在：' . $history['name']);
        }
        $data = [
            'name' => $name,
            'x' => $x,
            'y' => $y,
            'create_time' => time(),
        ];
        StationModel::insert($data);
        return $this->buildSuccess();
    }
    public function edit()
    {
        $id = $this->request->post('id', 0);
        $name = $this->request->post('name', '');
        $x = $this->request->post('x', 0);
        $y = $this->request->post('y', 0);
        $data = [
            'name' => $name,
            'x' => $x,
            'y' => $y,
        ];
        $history = StationModel::where([['name', '=', $name], ['id', '<>', $id]])->find();
        if ($history) {
            return $this->buildFailed(ReturnCode::UPDATE_FAILED, '该车站已存在：' . $history['name']);
        }
        if ($id) {
            StationModel::where(['id' => $id])->update($data);
        } else {
            $data['create_time'] = time();
            StationModel::insert($data);
        }
        return $this->buildSuccess();
    }
    public function del()
    {
        $id = $this->request->get('id', 0);
        if ($id) {
            StationModel::destroy($id);
        }
        return $this->buildSuccess();
    }
    public function changeStatus()
    {
        $id = $this->request->get('id');
        $status = $this->request->get('status');
        $res = StationModel::update([
            'id'     => $id,
            'status' => $status
        ]);
        if ($res === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR);
        }
        return $this->buildSuccess();
    }
    public function detail()
    {
        $data = [];
        return $this->buildSuccess($data);
    }
    public function getData()
    {
        $data = [
            'stations' => [],
            'lines' => []
        ];
        $stations = RailwayStationModel::alias('rs')
            ->join('station s', 's.id = rs.station_id')
            ->where([
                ['s.status', '=', 1],
            ])
            ->field('rs.*,rs.railway_id lineId,s.x,s.y')
            ->select()
            ->toArray();
        $lines = RailwayModel::with(['segments' => function ($query) {
            $query->field('id,railway_id,sort,name');
        }])
            ->where([])
            ->select()
            ->toArray();
        //        foreach ($stations as &$station) {
        //        }
        foreach ($lines as &$line) {
            $r = rand(0, 255);
            $g = rand(0, 255);
            $b = rand(0, 255);
            $line['title_color'] = 'rgba(' . $r . ',' . $g . ',' . $b . ',0.3)';
            $line['color'] = 'rgb(' . $r . ',' . $g . ',' . $b . ')';
            //            $line['title_color'] = 'rgb(173, 216, 230,0.5)';
            //            $line['color'] = 'rgb(72, 72, 72)';
            foreach ($line['segments'] as $key => &$segment) {
                $segment['start'] = $segment['id'];
                $segment['end'] = 0;
                if ($key != count($line['segments']) - 1) {
                    $segment['end'] = ($segment['id'] + 1);
                }
            }
            // 根据线路找当前check_record
            $checkRecord = CheckRecordModel::with(['check_item' => function($query) {
                $query->where([
                    ['delete_time', '=', null],
                    ['status', '<>', 3],
                    ['type', '=', 1]
                ]);
            }])->where([
                ['railway_id', '=', $line['id']],
                ['delete_time', '=', null],
                ['status', '<>', 3]
            ])->select();
            $line['check_record'] = $checkRecord;
        }
        $data['stations'] = $stations;
        $data['lines'] = $lines;
        return $this->buildSuccess($data);
    }
    public function unblock()
    {
        $rid = $this->request->post('rid', 0);
        $ids = $this->request->post('ids', []);
        
        if (count($ids) !== 2) {
            return $this->buildFailed(ReturnCode::PARAM_INVALID, '必须选择两个站点');
        }

        // 获取区间内的所有车站
        $stations = RailwayStationModel::where([
            ['railway_id', '=', $rid],
            ['id', '>=', min($ids)],
            ['id', '<=', max($ids)]
        ])->select();

        // 检查区间内所有车站是否都是完成状态
        foreach ($stations as $station) {
            if ($station->status !== 4) {
                return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '该区间内存在未完成的车站，无法解封');
            }
        }

        // 获取封锁记录
        $checkRecord = CheckRecordModel::where([
            ['railway_id', '=', $rid],
            ['start_id', '=', min($ids)],
            ['end_id', '=', max($ids)],
            ['delete_time', '=', null],
            ['status', '=', 2]  // 必须是完成状态
        ])->find();

        if (!$checkRecord) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '未找到对应的封锁记录或记录未完成');
        }

        // 检查该区间的所有检查项目是否都已完成
        $checkItems = CheckItemModel::where([
            ['check_record_id', '=', $checkRecord->id],
            ['delete_time', '=', null],
            ['status', '<>', 2]  // 检查是否有未完成的项目
        ])->find();

        if ($checkItems) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '该区间的检查项目尚未全部完成，无法解封');
        }

        Db::startTrans();
        try {
            // 更新站点状态
            RailwayStationModel::where([
                ['railway_id', '=', $rid],
                ['id', '>=', min($ids)],
                ['id', '<=', max($ids)]
            ])->update([
                'status' => 1,
                'check_item_ids' => null
            ]);

            // 更新检查记录状态
            $checkRecord->status = 3;
            $checkRecord->save();

            // 更新检查项目状态
            CheckItemModel::where([
                ['check_record_id', '=', $checkRecord->id],
                ['delete_time', '=', null]
            ])->update([
                'status' => 3
            ]);

            Db::commit();
            return $this->buildSuccess([], '解封成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, $e->getMessage());
        }
    }
}
